package com.java2007.hotel.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.java2007.hotel.dao.UserDao;
import com.java2007.hotel.dao.impl.UserDaoImpl;
import com.java2007.hotel.pojo.User;
import com.java2007.hotel.service.UserService;
import com.java2007.hotel.utils.JdbcUtils;
import com.java2007.hotel.utils.Md5Utils;

import java.sql.SQLException;
import java.util.Date;

/**
 * @author Reckeys
 * @version V1.0
 * @date 2021/01/25
 **/
public class UserServiceImpl implements UserService{
    private UserDao userDao = new UserDaoImpl();

    /**
     * 用户登陆
     * @param userName
     * @param userPassword
     * @return
     */
    @Override
    public User userLogin(String userName,String userPassword)  throws Exception{
        try {
            if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPassword)){
                throw new RuntimeException("用户名跟密码都不能为空");
            }
            User user = userDao.findUser(userName.trim());
            if(user == null) {
                throw new RuntimeException("用户名或密码不正确");
            }

            //密码判断
            String userPassword1 = user.getUserPassword();
            //将输入的密码加密
            String md5p = Md5Utils.md5(userPassword);
            //判断两者是否相同
            if (md5p.equals(userPassword1)){
                return user;
            }else {
                throw new RuntimeException("用户名或密码不正确");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("用户名或密码不正确");
        }
    }

    /**
     * 用户注册
     * @param user
     * @return
     * @throws SQLException
     */
    @Override
    public String userRegistere(User user) throws SQLException {
        try {
            if ("".equals(user.getUserName()) || "".equals(user.getUserPassword())){
                return "用户名和密码不能为空";
            }
            User findUsers = userDao.findUser(user.getUserName());
            if (findUsers == null){
                //设置用户的初始状态
                user.setUserCreateTime(new Date());
                user.setUserStatus(1);
                user.setUserRole(3);

                //将密码进行md5加密
                String md5p = Md5Utils.md5(user.getUserPassword());
                user.setUserPassword(md5p);
                user.setUserMoney(0L);
                JdbcUtils.startTransactions();

                userDao.addUser(user);
                JdbcUtils.commit();
                return "注册成功";
            }
            return "用户已存在";
        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtils.rollBack();
            return "注册失败";
        }

    }


    /**
     * 查询用户名是否重复
     * @param userName
     * @return
     */
    @Override
    public int findUserReChecking(String userName) throws SQLException {
        User user = userDao.findUser(userName);
        //判断用户是否存在，0：不存在 1：存在
        if (user == null){
            return 0;
        }
        return 1;
    }


}
